September 27 2016

Regular Expressions

Regular Expression Testers

Online:
http://www.phpliveregex.com/
http://regexr.com/
Offline:
https://github.com/gskinner/regexr

Search for PHP Short Tag <?

<\?(?!php)(?!xml)

YouTube URL Patterns

RegEx: 
^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&"'>]+)

Flag:
gm

PHP Function:
/**
 * Get Youtube video ID from URL
 *
 * @param string $url
 * @return mixed Youtube video ID or FALSE if not found
 *
 * How to use
 * if ($url) {
 *    $youtube = getYoutubeIdFromUrl($url);
 *    if (!$youtube) {
 *       $vid = $url;
 *    } else {
 *       $vid = 'https://www.youtube.com/embed/'.$youtube;                       
 *    }
 *    echo "View Video »";
 * } 
 */
function getYoutubeIdFromUrl($url) {
   $pattern = '#^(?:https?://)?(?:www\.)?(?:m\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
   preg_match($pattern, $url, $matches);
   return isset($matches[1]) ? $matches[1] : false;
}

Search Strings:
Here

UK Phone Patterns

RegEx 1 (Relax, allow phone number started with digit, ( or +, contains (, ), +, ' ', and any digit length between 6 to 20):
^[0-9\+\(][\+\(\)\s0-9]{5,20}$

RegEx 2 (Relax, allow phone number which contains at least 6 digits):
^\D*(?:\d\D*){6,}$

RegEx 3 (Strict):
^(\+?44)?(\(\d+\))?[\d ]+(#\d+)?